package neu.soft.listener;

import lombok.extern.slf4j.Slf4j;
import neu.soft.entity.FinancialPurchaseOrder;
import neu.soft.entity.OperationPurchaseOrder;
import neu.soft.exception.AppException;
import neu.soft.exception.AppExceptionCodeMsg;
import neu.soft.facade.SupplyComprehensiveFacade;
import neu.soft.vo.MsgBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
@Slf4j
public class SupplyListener {

    @Autowired
    SupplyComprehensiveFacade supplyComprehensiveFacade;

    /**
     *
     * @param msgBean 包含map，键为oid和shopping
     */
    //消息监听通道，与配置中配置的相应的消费者名称相同OperationPurchaseOrder
    @StreamListener("shortage-input")
    @SendTo("financial-supply-output") //类似回调，这里转发给了financial-supply-output这一名称的输出通道
    public OperationPurchaseOrder receiveSupplyMsg(@Payload MsgBean<Map<String, Object>> msgBean) {
        Map<String, Object> receiveMap = msgBean.getData();
        OperationPurchaseOrder operationPurchaseOrder = supplyComprehensiveFacade.consumeSupplyMsg(receiveMap);
        log.info(operationPurchaseOrder.toString());
        //调用财务中心服务，传递购货单
        return operationPurchaseOrder;
    }

    //收到财务中心的购货单，确认后发给中心库房
    @StreamListener("operation-supply-input")
    public void receivePurchaseMsg(@Payload MsgBean<FinancialPurchaseOrder> msgBean){
        FinancialPurchaseOrder financialPurchaseOrder = msgBean.getData();
        if (financialPurchaseOrder == null){
            throw new AppException(AppExceptionCodeMsg.QUERY_FAIL);
        }
        Integer purchaseOrderId = financialPurchaseOrder.getPurchaseOrderId();
        supplyComprehensiveFacade.sendWarehouseMsg(purchaseOrderId);
    }

}
